const Comment = require('../models/comments')

class Comments {
  async find(ctx) {
    // 每页大小
    const pageSize = Math.max((ctx.query.page_size || 10) * 1, 1)
    // 当前页
    const current = ctx.query.current * 1
    // 偏移量
    const offset = Math.max(current - 1, 0) * pageSize
    // 查询参数
    const reg = new RegExp(ctx.query.q)

    // NOTE: $or 表示二者之一
    const params = {
      content: reg,
      question_id: ctx.params.questionId,
      answer_id: ctx.params.answerId,
      root_comment_id: ctx.query.rootCommentId
    }

    const list = await Comment.find(params)
      .limit(pageSize)
      .skip(offset)
      .populate('commentator replay_to')

    ctx.body = list
  }

  async findById(ctx) {
    const { fields = '' } = ctx.query
    // example: name;avatar_url;introducation ---> name avatar_url introducation
    const str = fields.replaceAll(';', ' ')
    const comment = await Comment.findById(ctx.params.id)
      .select(str)
      .populate('commentator')
    ctx.body = comment
  }

  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true },
      root_comment_id: { type: 'string', required: false },
      replay_to: { type: 'string', required: false }
    })
    const params = {
      ...ctx.request.body,
      commentator: ctx.state.user._id,
      question_id: ctx.params.questionId,
      answer_id: ctx.params.answerId
    }
    const comment = await new Comment(params).save()
    ctx.body = comment
  }

  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false }
    })

    const comment = await Comment.findByIdAndUpdate(
      ctx.params.id,
      // 只允许更新评论内容
      ctx.request.body.content,
      {
        new: true
      }
    )
    ctx.body = comment
  }

  async delete(ctx) {
    await Comment.findOneAndDelete(ctx.params.id)
    ctx.status = 204
  }
}

module.exports = new Comments()
